package com.sc.nft.helper;
import cn.hutool.core.date.DateUtil;
import com.sc.nft.entity.UserPledgeRecords;
import com.sc.nft.service.PledgeTaskInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class UserPledgeRecordsHandler {
    private ScheduledExecutorService executor;

    @Resource
    private PledgeTaskInfoService pledgeTaskInfoService;

    public UserPledgeRecordsHandler() {
        executor = Executors.newSingleThreadScheduledExecutor();
    }

    public void start(List<UserPledgeRecords> records) {
        for (UserPledgeRecords record : records) {
            log.info("时间轮执行时间:{}", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            long delayInSeconds = calculateDelayInSeconds(record.getCompleteTime());
            executor.schedule(() -> handlePledgeRecord(record), delayInSeconds, TimeUnit.SECONDS);
        }
    }

    private long calculateDelayInSeconds(Date completeTime) {
        long currentTime = System.currentTimeMillis();
        long targetTime = completeTime.getTime();
        long delayInSeconds = (targetTime - currentTime) / 1000;
        return delayInSeconds < 1L ? 1L : delayInSeconds; // 转换为秒
    }

    private void handlePledgeRecord(UserPledgeRecords record) {
        pledgeTaskInfoService.updatePledgeTaskAwardStatus(record);
    }
}
